// global
var IMGURL =  '../imgs/';

var CVST = {
    init: function (lnk) {
        this.lnk = lnk || './';
    },
    getURL: function (uri) {
        return this.lnk + uri;
    }
};

/*****************************/
Elements.implement({
 filterByTag: function(tag) {
    return this.filter(tag);
 },
 filterByClass: function(className) {
    return this.filter('.' + className);
 },
 filterById: function(id) {
    return this.filter('#' + id);
 },
 filterByAttribute: function(name, operator, value) {
    return this.filter('[' + name + (operator || '') + (value || '') + ']');
 }
});

// This function formats numbers by adding commas
function numberFormat(str) {
    str = '' + str.toFixed(2);
    var x = str.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function toAlphaNumeric(s) {
    var val = '';
    var ch = '';
    for (var i = 0; i < s.length; i++) {
        ch = s.substring(i, i + 1);
        if (ch === '\'')
            continue;
        if (ch >= ' ' && ch <= '~')
            val += ch;
    }
    return val;
}
function isInt(s) {
    return (s % 1) === 0 ? s : 0;
}

function checkPassword() {
    var c = document.id('Customer');
    if (c.Password.value === c.vPassword.value)
        return;
    else {
        alert("Your passwords do not match");
        c.Password.value = '';
        c.vPassword.value = '';
        c.Password.focus();
        return;
    }
}

function isCreditCard(ss) {
    var val = ss.value.replace(/-/g, '').replace(/ /g, '');
    var ck = parseInt(val, 10);
    if (!ck)
        return '';
    var sum = 0, mul = 1, l = val.length;
    for (var i = 0; i < l; i++) {
        var digit = val.substring(l - i - 1, l - i);
        var tproduct = parseInt(digit, 10) * mul;
        (tproduct >= 10) ? sum += (tproduct % 10) + 1 : sum += tproduct;
        (mul === 1) ? mul++ : mul--;
    }
    if (val.length !== '' && (sum % 10) === 0)
        return(val);
    else {
        alert("Check yours card number: " + val);
        ss.focus();
    }
    return '';
}

function isDone(f) {
 if(!f.Password.value) {
     alert("Password cannot be empty."); f.Password.focus(); return false;
 }
 if(f.vPassword.value !== f.Password.value) {
     alert("Your passwords do not match."); f.vPassword.focus(); return false;
 }
 if(!f.billingFirstName.value) {alert("Billing First Name are required.");f.billingFirstName.focus();return false;}
 if(!f.billingLastName.value) {alert("Billing Last Name are required.");f.billingLastName.focus();return false;}
 if(!f.billingAddress1.value) {alert("Billing Address1 are required.");f.billingAddress1.focus();return false;}
 if(!f.billingCountry.value) {alert("Billing Country are required.");f.billingCountry.focus();return false;}
 if(!f.billingCity.value) {alert("Billing City are required.");f.billingCity.focus();return false;}
 if(!f.billingState.value) {alert("Billing State are required.");f.billingState.focus();return false;}
 if(!f.billingZip.value) {alert("Billing Zip are required.");f.billingZip.focus();return false;}
 if(!f.billingPhone.value) {alert("Phone are required.");f.billingPhone.focus();return false;}
 if(!f.shippingFirstName.value) {alert("Shipping First Name are required.");f.shippingFirstName.focus();return false;}
 if(!f.shippingLastName.value) {alert("Shipping Last Name are required.");f.shippingLastName.focus();return false;}
 if(!f.shippingAddress1.value) {alert("Shipping Address1 are required.");f.shippingAddress1.focus();return false;}
 if(!f.shippingCountry.value) {alert("Shipping Country are required.");f.shippingCountry.focus();return false;}
 if(!f.shippingCity.value) {alert("Shipping City are required.");f.shippingCity.focus();return false;}
 if(!f.shippingState.value) {alert("Shipping State are required.");f.shippingState.focus();return false;}
 if(!f.shippingZip.value) {alert("Shipping Zip are required.");f.shippingZip.focus();return false;}
 if(!f.shippingPhone.value) {alert("Phone are required.");f.shippingPhone.focus();return false;}
 if(f.billingCountry.value === 'US' && !isInt(f.billingZip.value)){alert("Invalid Billing Zip.");f.billingZip.focus();return false;}
 if(f.shippingCountry.value === 'US' && !isInt(f.shippingZip.value)){alert("Invalid Shipping Zip.");f.shippingZip.focus();return false;}
 return true;
}
function copyBillToShipp(){
var c = document.id('Customer');
c.shippingCompany.value=c.billingCompany.value;
c.shippingFirstName.value=c.billingFirstName.value;
c.shippingLastName.value=c.billingLastName.value;
c.shippingAddress1.value=c.billingAddress1.value;
c.shippingAddress2.value=c.billingAddress2.value;
c.shippingCity.value=c.billingCity.value;
c.shippingZip.value=c.billingZip.value;
c.shippingZip4.value=c.billingZip4.value;
c.shippingState.value=c.billingState.value;
c.shippingCountry.value=c.billingCountry.value;
c.shippingPhone.value=c.billingPhone.value;
c.shippingCell.value=c.billingCell.value;
c.shippingFax.value=c.billingFax.value;
}

function resisDone(f){
 if(!f.Password.value){alert("Password cannot be empty.");f.Password.focus();return false;}
 if(f.vPassword.value !== f.Password.value){alert("Your passwords do not match.");f.vPassword.focus();return false;}
 if(!f.billingCompany.value){alert("Company name are required.");f.billingCompany.focus();return false;}
 if(!f.resellerCode.value){alert("Reseller code are required.");f.resellerCode.focus();return false;}
 if(!f.billingFirstName.value){alert("First Name are required.");f.billingFirstName.focus();return false;}
 if(!f.billingLastName.value){alert("Last Name are required.");f.billingLastName.focus();return false;}
 if(!f.billingAddress1.value){alert("Address1 are required.");f.billingAddress1.focus();return false;}
 if(!f.billingCountry.value){alert("Country are required.");f.billingCountry.focus();return false;}
 if(!f.billingCity.value){alert("City are required.");f.billingCity.focus();return false;}
 if(!f.billingState.value){alert("State are required.");f.billingState.focus();return false;}
 if(!f.billingZip.value){alert("Zip are required.");f.billingZip.focus();return false;}
 if(!f.billingPhone.value){alert("Phone are required.");f.billingPhone.focus();return false;}
 if(!f.billingZip.value){alert("Zip are required.");f.billingZip.focus();return false;}
 if(!f.billingPhone.value){alert("Phone are required.");f.billingPhone.focus();return false;}
 return true;
}

function isEmail(string){
 return string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) !== -1 ? true : false;
}

function isReady(f){
 if(! isEmail(f.Email.value)) {
  alert("Please enter a valid email address.");
  f.Email.focus();
  return false;
 }
 if(! f.Password.value) {
  alert("Password cannot be empty.");
  f.Password.focus();
  return false;
 }
 if(f.mode.value === 'new') {
  if(f.vPassword.value !== f.Password.value) {
   alert("Your passwords do not match.");
   f.vPassword.focus();
   return false;
  }
 }
 return true;
}

var sIs = new Array("","one","two","three","four","five","six","seven","eight","nine");
var dIs = new Array("","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen");
var tIs = new Array("","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety");
var qIs = new Array("","thousand","million","billion");
function NtoW() {
  var x = document.id("nsu").firstChild.nodeValue.split('\$');
  n2w(x[1]);
}
function sdt(a) {
    var s = "", i = a % 10;
    if (i > 0)
        s = sIs[i];
    var j = Math.floor((a % 100) / 10);
    if (j === 1)
        s = dIs[i + 1];
    else if (j > 1 && j < 10)
        s = tIs[j - 1] + " " + s;
    i = Math.floor(a / 100);
    if (i > 0)
        s = sIs[i] + " hundred " + s;
    return s;
}
function n2w(a) {
    var i = 0, k = 0, s = '';
    if (a) {
        var t = a.split('.', 2);
        i = parseInt(t[0].replace(/,/g, ''));
    }
    if (i > 0 && i < 2147483647) {
        for (var j = 0; j < 4; j++) {
            k = i % 1000;
            i = Math.floor(i / 1000);
            if (k > 0)
                s = sdt(k) + ' ' + qIs[j] + ' ' + s;
        }
    }
    k = parseInt(t[1], 10);
    if (k < 10 && t[1].length === 1)
        k *= 10;
    if (k > 0)
        s += ' and ' + k + ' cents';
    document.id('am').set('html', '<i>' + s + '</i>');
}

function validPromo() {
 var a = document.id('promo').value;
 if(a) {
  a = a.toUpperCase();
  if(a.length < 7 || a.charAt(0) !== 'C' && a.charAt(1) !== 'V') {
    alert("We're sorry, but this promotion code is invalid.");
    return false;
  }
  document.id('Basket').submit();
 }
 else{
    alert("Promotion code empty.");
 }
 return true;
}

function prestart() {
    var pref = document.id('pref');
    if (!pref)
        return;
    var div = pref.getElements('div.al');
    if (!div)
        return;
    for (var i = 0; i < div.length; i++) {
        fcl(div[i].getParent().get('id'));
    }
}

function fcl(a) {
    var x = document.id(a);
    if (!x)
        return;
    var im = x.getPrevious('a').getFirst('img');
    if (x.style.display === 'block') {
        x.setStyle('display', 'none');
        im.set('src', '../img/it/pls.png');
    }
    else {
        var y = x.getElements('a');
        if (y.length > 12) {
            x.setStyles({'height': '200px', 'overflow': 'auto', 'border-top': '1px solid #BFB8BF', 'border-bottom': '1px solid #BFB8BF'});
        }
        else {
            x.setStyles({'height': 'auto', 'border-top': 0, 'border-bottom': 0});
        }
        x.setStyles({'width': '100%', 'display': 'block'});
        im.set('src', '../img/it/mns.png');
    }
    x = im = y = null;
}

function hideErr(a) {
 a.style.visibility = 'hidden';
}

/* +paymant.jsp */
function isPaymentDone(form) {
    var tbs = document.id('cvTabs');
    if(!tbs) {
      alert("Not find tabs");
    }
    var tabs = tbs.getElements('a.tab');
    var payment = tabs.filterByClass('active').get('href');
    document.id('payMethod').set('value', payment);

    if(!form.totb.value) {
        alert("Please choose one Shipping Methods!");
        return false;
    }
    else {
        if(payment === 'CC') {
            if(!form.CNumber.value){ alert("Credit card Number required!");form.CNumber.focus();return false;}
            if(!form.CExpMonth.value){ alert("Credit card Month required!");form.CExpMonth.focus();return false;}
            if(!form.CExpYears.value){ alert("Credit card Years required!");form.CExpYears.focus();return false;}
        }
        else if(payment === 'CD') {
            if(!form.checkNumber.value && !form.checkNumber.value.test(/^\d{4}/g)){ alert("Check Number required!\nMust be digits");form.checkNumber.focus();return false;}
            if(!form.checkAccount.value && !form.checkAccount.value.test(/^\d{10}/g)){ alert("Check Account Number required!\nMust be digits");form.checkAccount.focus();return false;}
            if(!form.checkRouting.value && !form.checkRouting.value.test(/^\d{9}/g)){ alert("Check Routing Number required!\nMust be digits");form.checkRouting.focus();return false;}
            if(!form.licenseNumber.value && !form.licenseNumber.value.test(/^[a-z][A-Z]\d/g)){ alert("License Number required!");form.licenseNumber.focus();return false;}
            if(!form.licenseState.value && !form.licenseState.value.test(/^[A-Z]{2}/g)){ alert("License USA State required!");form.licenseState.focus();return false;}
        }
    }
    form.mode.disabled = 'disabled';

    return true;
}

var setGroundShipping = new Class({
    Implements: Options,
    options: {
        'data': []
    },
    initialize: function(opts) {
        this.setOptions(opts);

        if(!this.options.data.length) return;

        this.taxField = document.id('taxb');
        this.descField = document.id('desb');
        this.desview = document.id('desview');
        this.shipPrice = document.id('spb');
        this.shipMethod = document.id('scdb');
        this.totalField = document.id('totb');
        this.signout = document.id('sgnout');
        this.sign = document.id('sgnch');

        // if international no need default fill
        if(this.options.data[0].shmd !== 'uspsx') {
            this.setDefault();
        }
    },
    setDefault: function() {

        this.firshShip = this.options.data[0];
        this.fillFields(this.firshShip);
    },
    setShipping: function(shipmed) {

        var item = this.options.data.filter(function(ship) {
            return ship.shmd === shipmed;
        });

        var shipBlock = item[0];
        if(shipBlock) {
            if(shipBlock.shmd === 'usps' || shipBlock.shmd === 'uspsx') {
                var answer = confirm("USPS shipments do NOT carry insurance. I acknowledge that choosing USPS as the carrier, Compuvest Corporation is not responsible for any loss or damage once the shipment leaves Compuvest's facility");
                if(!answer) {
                    this.setDefault();
                    return;
                }
            }
            this.fillFields(shipBlock);
        }
    },
    setSign: function() {

        this.signChecked = this.sign.get('checked');

        if(this.signChecked) {
            this.signout.set('html', 'Signature: <input name="sgn1" value="$2.00" size="10" readonly/>');
        }
        else {
            this.signout.empty();
        }
        var checkedMethod = $$('input[name=ship_opt]:checked')[0].get('value');

        var item = this.options.data.filter(function(ship) {
            return ship.shmd === checkedMethod;
        });

        var shipBlock = item[0];
        this.fillFields(shipBlock);
    },
    fillFields: function(block) {

        this.signChecked = this.sign.get('checked');
        if(block) {
            document.id(block.shmd).set('checked', true);
            this.taxField.set('value', '$' + block.tax.toFixed(2));
            this.descField.set('value', block.shdesc);
            this.desview.set('text', block.shdesc + ' : ');
            this.shipPrice.set('value', '$' + block.shprc.toFixed(2));
            this.shipMethod.set('value', block.shmd);
            this.totalField.set('value', '$' + (block.total + (this.signChecked ? block.sgprc : 0)).toFixed(2));
        }
    }
});
/* -paymant.jsp */

function reset() {
  return false;
}

function sendform(formname) {
 var result = true;
 switch(formname){
  case 'notfound':
  case 'quoterequest':
  case 'volumediscount': if(checkf(formname)) document.forms[formname].submit(); break;
  case 'logto':          if(checklogto()) document.forms['logto'].submit(); break;
  case 'forgotm':        if(checadr()) document.forms['forgotm'].submit(); break;
  default: result = false;
 }
 return result;
}

function checkf(a) {
 var current;
 for(var i = 1; i < 4 ; i++) {
  current = document.forms[a].elements[i];

  if(!current.value) {
   alert('You haven\'t filled in ' + '\"' + current.name + '\"' + ' !');
   return false;
  }
 }
 return cem(document.forms[a].elements[3].value);
}

function checadr(){
 var current = document.forms['forgotm'].elements[0];
 if(!cem(current.value)) return false;
 return true;
}

var vv = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
function checklogto(){
 var current = document.forms['logto'].elements[0];
 if(!cem(current.value)) return false;
 current = document.forms['logto'].elements[1];
 var s = current.value;
 var t = 1;
 if(s) {
  for(var i=0; i < s.length; i++) {
   if(vv.indexOf(s.charAt(i)) === -1) {
       t = 0;
       break;
   }
  }
 }
 if(!s || !t){
  alert('Your password is not valid!');
  return false;
 }
 return true;
}

function cem(email) {
 if(! isEmail(email)){
  alert("Please enter a valid email address.");
  return false;
 }
 return true;
}

//-------------------------
//
var ItemsShow = new Class({
 initialize:function(elm, pageName, firstPage){
  this.itemsdiv = document.id(elm);
  if(!this.itemsdiv) return;

  // category tags
  this.needChangeCat = 1; // need change category
  this.catsdiv = document.id('catshow');
  this.catID = 0;
  this.catName = '';

  // preference
  this.loPrice = 0;
  this.hiPrice = 0;
  this.pref = new Array();

  // navigator line
  this.nav = document.id('navgshow');
  this.ctnav = '';

  this.firstPage = firstPage; // if null show items, or advert
  this.pageName = pageName;
  this.pageBack = document.location.href;
  this.items = {};

  this.pageNo = 0; // current page No
  this.itemOnPage = 15; //default items on page
  this.sort = 3; // sort Relevance

  this.getItems();
 },
 getItems: function() {
  var pref = '';
  for(var i=0; i < this.pref.length; i++){
    if(this.pref[i]){
        pref += '&p' + i + '=' + this.pref[i];
    }
  }
  new Request({
      url: "getitems",
      onRequest : function() {
          this.itemsdiv.empty();
          this.itemsdiv.setStyle('text-align','center');
          this.itemsdiv.adopt(new Element('img[src=../img/wait.gif][alt=wait]'));
      }.bind(this),
      onSuccess: function(items) {
        if(!items.length) {
            alert('We have found 0 items that match');
            return;
        }
        try {
          this.items = eval('(' + items + ')');
        }
        catch(err){ alert('itemshow Error...');return; }

       this.doIt();
      }.bind(this),
      onFailure : function(err) { alert('Error... ' + err); }
  }).send(
    'cp=' + this.getCatPage() + '&pg=' + this.pageNo + '&iop=' + this.itemOnPage+ '&sr=' + this.sort +
    '&cid=' + this.catID + '&nc=' + this.needChangeCat +
    '&lp=' + this.loPrice + '&hp=' + this.hiPrice + pref +
    '&nh=' + Math.random()
  );
//   parameters:'cp='+this.getCatPage()+'&cid='+this.catID+'&pg='+this.pageNo+'&nc='+this.needChangeCat+'&bn='+this.brand+
//              '&sr='+this.sort+'&lp='+this.loPrice+'&hp='+this.hiPrice+pref+'&iop='+this.itemOnPage+'&nh='+Math.random(),
 },
 doIt:function() {

  if(this.needChangeCat) {
   // navigation line
   if(this.nav) {
//    startTime = Date.now();
    this.nav.empty();

    this.ctnav = new Element('div#ctnav');
    this.ctnav.adopt(new Element('tt[html=&#8226;]'));
    this.ctnav.adopt(new Element('a[href=' + CVST.getURL('') + '][text=Home]'));
    this.ctnav.adopt(new Element('tt[html=&#8226;]'));
    this.ctnav.adopt(new Element('a[href=' + this.pageBack + '][html=' + this.pageName + ']'));
    this.ctnav.adopt(new Element('tt[html=&#8226;]'));

    if(this.catName) {
        var a = new Element('a[href=#][html=' + this.catName + ']', {
            'events': {
                'click': function() {
                    this.pageNo = 0;
                    this.sort = 1;
                    this.loPrice = this.hiPrice = 0;
                    for(var i=0; i < this.pref.length; i++) {
                        if(this.pref[i]) {
                            this.pref[i] = null;
                        }
                    }

                    this.needChangeCat = 1;
                    this.getItems();
                }.bind(this)
            }
        });
        this.ctnav.adopt(a);
        this.ctnav.adopt(new Element('tt[html=&#8226;]'));
    }

    this.nav.adopt(this.ctnav);
   }
    // category or preference
    if(this.catsdiv) {
        this.catsdiv.empty();
        if(this.items.cts.length){
            this.catsdiv.adopt(this.doCats());
        }
        else if(this.items.prf.length) {
            this.catsdiv.adopt(this.doPref());
        }
    }
  }//this.needChangeCat


  this.itemsdiv.empty();

  //show items
  this.pages = parseInt((this.items.cnt % this.itemOnPage === 0) ? this.items.cnt / this.itemOnPage : this.items.cnt / this.itemOnPage + 1);

  this.itemsdiv.adopt(this.doTop());
  this.itemsdiv.adopt(new Items(this.items));
  this.itemsdiv.adopt(this.doBot());
  this.itemsdiv.adopt(this.doPager());

  new Tipz('img.tipzb');

  new DialogBox('a.drpab'); // drop price alert

 },
 doTop: function() {
  var pg = (this.pageNo + 1) * this.itemOnPage;
  var div = new Element('div#ittop');
  var tbody = new Element('tbody');
  var tr = new Element('tr');
  new Element('td.fl1', {
      'html': ((this.pageNo * this.itemOnPage) + 1) + ' - ' + pg >= this.items.cnt ? this.items.cnt : pg + ' of ' + this.items.cnt + ' results'
  }).inject(tr);

  var td = new Element('td.fl3');

  var selp = new Element('select', {
    'events': {
        'change': function(ev) {
            ev.stop();
            this.sort = parseInt(ev.target.value);

            this.needChangeCat = 0;
            this.pageNo = 0;
            this.getItems();
        }.bind(this)
    }
  }).inject(td);

  new Element('option[value=1]' + (this.sort === 1 ? '[selected=yes]' : '') + '[text=Price: low to high]').inject(selp);
  new Element('option[value=2]' + (this.sort === 2 ? '[selected=yes]' : '') + '[text=Price: high to low]').inject(selp);
  new Element('option[value=3]' + (this.sort === 3 ? '[selected=yes]' : '') + '[text=Relevance]').inject(selp);

  var selc = new Element('select[style=width:45px;]',{
    'events': {
        'change': function(ev) {
            ev.stop();
            this.itemOnPage = parseInt(ev.target.value);

            this.needChangeCat = 0;
            this.pageNo = 0;
            this.getItems();
        }.bind(this)
    }
  }).inject(td);

  new Element('option[value=15]' + (this.itemOnPage === 15 ? '[selected=yes]' : '') + '[text=15]').inject(selc);
  new Element('option[value=25]' + (this.itemOnPage === 25 ? '[selected=yes]' : '') + '[text=25]').inject(selc);
  new Element('option[value=50]' + (this.itemOnPage === 50 ? '[selected=yes]' : '') + '[text=50]').inject(selc);

  div.adopt(new Element('table#iborder').adopt(tbody.adopt(tr.adopt(td))));
  return div;
 },
 doBot: function() {
    return new Element('div#itbot', {'html':
        '<table id="iborder" style="line-height:18px">' +
        '<tbody>' +
        '<tr>' +
        '<td class="fl1">Page: ' + (this.pageNo + 1) + ' of ' + this.pages + '</td>' +
        '<td class="fl3" style="font-size:9px;">' + this.items.t + '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>'
    });
 },
 doPager: function() {
    var div = new Element('span[style=line-height:26px;]');
    if(this.pages !== 1){
        var page = this.pageNo + 1, start = 1,end = this.pages,offSetEnd = false,elm;

        if(this.pages - page > 9){
            end = page + 9;
            offSetEnd = true;
        }
        // left arrow
        elm = new Element('a#0[html=&laquo;&nbsp;]');
        if(page !== 1){
            elm.set({
                'id': page - 2,
                'href': '#',
                'events': {
                    'click': this.goPage.bind(this)
                }
            });
        }
        div.adopt(elm);
        //
        if(page > 10) {
            start = page - 9;
            new Element('a#0[href=#][text=1 . . .]', {
                'events':{
                    'click': this.goPage.bind(this)
                }
            }).inject(div);
        }

        for(var pg = start; pg <= end; pg++) {
            elm = new Element('a[html=&nbsp;' + pg + '&nbsp;]');
            if(pg === page){
                elm.set('style', 'font-size:18px;color:#800000;');
            }
            else {
                elm.set({
                    'id': pg - 1,
                    'href': '#',
                    'events':{
                        'click': this.goPage.bind(this)
                    }
                });
            }
            div.adopt(elm);
        }

        if(offSetEnd) {
            new Element('a#' + (this.pages - 1) + '[href=#][html=. . . ' + this.pages + ']', {
                'events':{
                    'click': this.goPage.bind(this)
                }
            }).inject(div);
        }
        // right arrow
        elm = new Element('a#0[html=&nbsp;&raquo;]');
        if(page !== this.pages) {
            elm.set({
                'id': page,
                'href': '#',
                'events':{
                    'click': this.goPage.bind(this)
                }
            });
        }
        div.adopt(elm);
    }
    return div;
},
goPage: function(ev) {
 ev.stop();
 this.pageNo = parseInt(ev.target.id);

 this.needChangeCat = 0;
 this.getItems();
},
doCats: function() {
  var div = new Element('div#ctmenu'),ul,li,a;
  div.adopt(new Element('div.top'));
  var dv = new Element('div#ctwm');
  var is;
  for(var i = 0; i < this.items.cts.length; i++) {
    var cat = this.items.cts[i];
    if(is !== cat.p) {
        is = cat.p;
        ul = new Element('ul');
        li = new Element('li#gct' + i + '.gct[html=' + cat.nmg + '<tt>(' + this.countItem(cat.p) + ')</tt>]', {
            'events': {
                'click': function() {
                    var elm = document.id(this.id + '0');
                    elm.setStyle('display', elm.getStyle('display') === 'none' ? '' : 'none');
                }
            }
        });
        ul.adopt(li);
        dv.adopt(ul);

        ul = new Element('ul#gct' + i + '0[style=display:none;]');
        dv.adopt(ul);
    }

    li = new Element('li[html=&raquo;]');
    a = new Element('a#' + cat.id + '[href=#][html=' + cat.nm + ']', {
        'events': {
            'click': function(ev) {
                this.catID = parseInt(ev.target.id);
                this.catName = ev.target.innerHTML;

                this.needChangeCat=1;
                this.pageNo = 0;
                this.getItems();
            }.bind(this)
        }
    });
    li.adopt(a);
    li.adopt(new Element('tt[html=(' + cat.n + ')]'));

    ul.adopt(li);
  }//for

   //open cat if less 50 lines small
   if(i < 50) {
    dv.getElements('ul[id]').setStyle('display','block');
   }

  div.adopt(dv);
  div.adopt(new Element('div.bot'));

  return div;
 },
 countItem: function(id) {
  var cnt = 0;
  this.items.cts.each(function(elm) {
    if(id === elm.p)
        cnt += elm.n;
  });
  return cnt;
 },
 doPref:function(){
  var div = new Element('div#ctmenu'),pl,prf,ul,li,lih,lim;
  div.adopt(new Element('div.top'));

  var dv = new Element('div#ctwm');
  dv.adopt(new Element('div.hd[text=Search by preference]'));

  if(this.loPrice && this.hiPrice) {
   pl = new Element('nobr[text=Price Range]');
   new Element('a[style=color:red;][title=Clean Price Range][href=#][text= (x)]', {
       'events': {
           'click': function() {
                this.needChangeCat = 1;
                this.loPrice = this.hiPrice = 0;
                this.getItems();
           }.bind(this)
       }
   }).inject(pl);
   dv.adopt(pl);
  }
  else{
   dv.adopt(new Element('nobr[text=Price Range]'));
  }
  dv.adopt(this.makeForm());

  for(var ip = 0; ip < this.items.prf.length; ip++) {
    prf = this.items.prf[ip];
    dv.adopt(
        new Element('hr[style=border:1px dotted silver;margin-top:2px;]'),
        new Element('nobr[html=' + prf.nm + ']')
     );

    ul = new Element('ul');
    lih = '';
    prf.pl.sort(this.filter); // sorting

    for(var ix=0; ix < prf.pl.length; ix++) {
        pl = prf.pl[ix];
        if(pl.nm) {
            li = new Element('li');
            if(this.pref[pl.id]) {//selected
                li.adopt(new Element('tt[style=color:red;][html=&raquo; <a href="#" style="color:gray;">' + pl.nm + '</a><tt>(' + pl.cn + ')</tt>]'));
                new Element('a#' +pl.id + '[style=color:red;][title=Clean ' + pl.nm + '][href=#][text=(x)]', {
                    'events': {
                        'click': this.doRemove.bind(this)
                    }
                }).inject(li);

                // navig
                this.ctnav.adopt(new Element('a', {'href': '#', 'style': 'color:gray;', 'html': pl.nm}));
                new Element('a#' + pl.id + '[style=color:red;][title=Clean ' + pl.nm + '][href=#][text=(x)]', {
                    'events': {
                        'click': this.doRemove.bind(this)
                    }
                }).inject(this.ctnav);
                this.ctnav.adopt(new Element('tt[html=&#8226;]'));
            }
            else {
                li.adopt(new Element('tt', {'html': '&raquo; '}));
                new Element('a#' + pl.id + '[title=' + pl.nm + '][href=#][html=' + pl.nm + ']', {
                    'events': {
                        'click': function(ev) {
                            ev.stop();
                            var a = ev.target;
                            this.pref[a.id] = a.title;

                            this.pageNo = 0;
                            this.needChangeCat = 1;
                            this.getItems();
                        }.bind(this)
                    }
                }).inject(li);

                li.adopt(new Element('tt[html=(' + pl.cn + ')]'));
            }

            //more or hide pref
            if(ix === 5) {
                lim = new Element('li#pb' + ip + '.mh[html=<tt class="hd">&darr;</tt> More ...]', {
                    'events': {
                        'click': function(ev) {
                            ev.stop();
                            var li = ev.target;
                            var id = document.getElementById(li.id);
                            id.setStyle('display', 'none');
                            id = document.getElementById(li.id + '_h');
                            id.setStyle('display', 'block');
                        }
                    }
                });
                ul.adopt(lim);
                dv.adopt(ul);

                ul = new Element('ul#pb' + ip + '_h[style=display:none;]');

                lih = new Element('li#b' + ip + '.mh[html=<tt class="hd">&uarr;</tt> Hide]', {
                    'events': {
                        'click': function(ev) {
                            ev.stop();
                            var li = ev.target;
                            var id = document.getElementById('p' + li.id + '_h');
                            id.setStyle('display', 'none');
                            id = document.getElementById('p' + li.id);
                            id.setStyle('display', 'block');
                        }.bind(this)
                    }
                });
            }
            ul.adopt(li);
        }//if
   }//for 2
   if(lih){ //insert hide
    ul.adopt(lih);
   }
   dv.adopt(ul);

  }//for 1
  div.adopt(dv);
  div.adopt(new Element('div.bot'));

  return div;
 },
 doRemove: function(ev) {
  ev.stop();
  var a = ev.target;
  this.pref[a.id] = null;

  this.needChangeCat = 1;
  this.getItems();
 },
 makeForm: function() { // search low price - hi price
  var frm = new Element('form', {
      'html':
        '<tt> $</tt><input type="text" value="' + this.loPrice + '"/><tt> - $</tt>' +
        '<input type="text" value="' + this.hiPrice + '"/><input type="submit" value="Go"/>',
      'events': {
          'submit': function(ev) {
                ev.stop();
                var inps = ev.target.getElements('input[type="text"]');
                this.loPrice = parseInt(inps[0].value);
                this.hiPrice = parseInt(inps[1].value);
                if(inps.length > 1 && this.loPrice && this.hiPrice && (this.hiPrice > this.loPrice)) {
                    this.needChangeCat = 1;
                    this.getItems();
                }
                else{
                    alert('Price Range can\'t be zero or be empty.');
                    inps[0].focus();
                    inps[0].select();
                }
          }.bind(this)
      }
  });
  return frm;
 },
 // return what kind page Clearance Special Search etc...
 getCatPage: function() {
  var pg = document.location.href.match(/\bcp=\b(\d+)/);
  if(pg) {
   pg = pg[1] || 1;
  }
  return pg;
 },
 filter: function(a, b) {
  return a.nm < b.nm ? -1 : a.nm > b.nm ? 1 : 0;
 }
});

//---------------------------
//
// Element.Position for align center

var dropmessg = {
 before: {
     text:
  '<p>Dear CompuVest Customer!</p><br/><p>Welcome to Compuvest Price Drop Alerts, where you can sign up to receive alerts \
  for price changes on your favorite products, direct to your email. Subscribe for Instant Email Alerts. \
  Complete the form and click the Submit button to set an Alert.</p><br/>'
 },
 after: {
     text:
  '<br/><p>Dear Customer!</p><br/><p>Thank you for submitting your price-drop alert. If the price drops within the specified \
  time-frame you will be notified by email (or phone).</p><p>Please feel free to contact us if any questions.</p><br/>'
}
};
var DialogBox = new Class({
 initialize:function(tags) {
  this.tags = $$(tags);
//  console.log('$$(tags)=',$$(tags));
//  console.log('getElements=',document.getElements(tags));
  if(!this.tags.length) return;
  this.body = ''; // div body
  this.width = 500; // contaner width

  this.box = document.id('dropricebox'); // div contaner
  if(!this.box) {
    this.dropBox();
  }

  this.overlay = document.id('overlay'); // fade screen
  if(!this.overlay) {
    this.tagOverlay();
  }
  this.overlay.addEvent('click', this.hide.bind(this));

  this.tags.each(function(tag) {
    tag.addEvent('click', this.show.bind(this, tag.id));
  }, this);

  this.fade = new Fx.Morph(this.overlay).set({'opacity': 0});
 },
 dropBox: function() {
  this.box = new Element('div#dropricebox[style=visibility:hidden;opacity:0;width:' + this.width + 'px;]').inject(document.body, 'top'); // opacity ie fixed
 },
 tagOverlay: function() {
  this.overlay = new Element('div#overlay[style=visibility:hidden;opacity:0;]').inject(document.body, 'top'); // opacity ie fixed
 },
 show: function(iid) {
  document.addEvent('keydown', function(ev) {
    if(ev.key === 'esc' && this.box.getStyle('visibility') === 'visible') {
     this.hide();
    }
  }.bind(this));

  new Request({
      url: 'droprice',
      onSuccess: function(item) {
        this.doForm(eval('(' + item + ')'));
      }.bind(this),
      onFailure : function(err) { alert('Error... ' + err); }
  }).send('iid=' + iid + '&act=it');
 },
 doForm: function(item) {
  this.box.empty();

  //make head
  var div = new Element('div#drophead');
  new Element('div[text=Price Drop Alerts]').inject(div);
  new Element('span[title=Close][text=x]', {
    'events': {
        'click': this.hide.bind(this)
    }
  }).inject(div);
  this.box.adopt(div);

  this.body = new Element('div#retdrop[html=' + dropmessg['before'].text + ']');
  var tbody = new Element('tbody').adopt(
   new Element('tr[html=<th width="27%">Product Code:</th><td width="73%">' + item.sku + '</td>]'),
   new Element('tr[html=<th>Product Name:</th><td>' + item.name + '</td>]'),
   new Element('tr[html=<th style="color:red;">Price:</th><td>$' + numberFormat(item.price) + '</td>]'),
   new Element('tr[html=<th style="color:green;">Notify me if:</th><td>Price changes</td>]'),
   new Element('tr[html=<th>Email:</th><td><input type="text" size="40" maxLength="128" name="email" value=""/></td>]'),
   new Element('tr[html=<th>Name:</th><td><input type="text" size="40" maxLength="40" name="name" value=""/></td>]'),
   new Element('tr[html=<th>Phone:</th><td><input type="text" size="40" maxLength="40" name="phone" value=""/></td>]'),
   new Element('tr[html=<td colspan=2>If you wish to be notified by phone, please enter you phone number.</td>]')
  );
  var input = new Element('input[type=submit][value=Send]', {
    'events': {
        'click': this.send.bind(this, item.id)
    }
  });
  tbody.adopt(new Element('tr[align=center]').adopt(new Element('td[colspan=2]').adopt(input)));

  this.body.adopt(new Element('table#drp_al').adopt(tbody));
  this.box.adopt(this.body);

  this.box.setPosition({x: (window.getSize().x / 2) - (this.width / 2), y: window.getScroll().y + window.getSize().y / 4});

  this.fade.start({'opacity':[0,0.7], 'visibility':'visible'});
  this.box.fade('in');
 },
 hide: function() {
  this.box.fade('out');
  this.fade.start({'opacity':[0,0.7], 'visibility':'hidden'});
 },
 send: function(itemid) {
  var parm = '';
  var email = false;
  var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // check email
  var inputs = this.box.getElements('input[type="text"]');
  inputs.each(function(input) {
    if(input.name === 'email') {
        email = pattern.test(input.value);
    }
    parm += '&' + input.name + '=' + input.value;
  });
  if(email) {
    new Request({
        url: 'droprice',
        onRequest : function() {
            this.body.empty();
            this.body.setStyle('text-align','center');
            this.body.adopt(new Element('img[src=../img/wait.gif][alt=wait]'));
        }.bind(this),
        onSuccess: function() {
            this.sendEmail();
        }.bind(this),
        onFailure : function(err) { alert('Error... ' + err); }
    }).send('act=sd&iid=' + itemid + parm);
  }
  else {
   alert('Please enter a valid email address.');
  }
 },
 sendEmail:function() {
  this.body.empty();
  this.body.set({'html': dropmessg['after'].text, 'style': 'text-align:left'});
 }
});
window.addEvent('domready', function(){ new DialogBox('a.drpa'); });

//---------------------------
//
var AdvertShow = new Class({
 Implements: Options,
 options: {
    id: 'advshow',
    data: [],
    cols: 5,
    count: 10
 },
 initialize:function(options) {
  this.setOptions(options);

  this.id = document.id(this.options.id);
  if(!this.id) return;

  this.show(this.options.data);
 },
 show:function(items) {
    var tbody = new Element('tbody'), tr = new Element('tr[align=center]');
    items.sort(function() { return 0.5 - Math.random(); }).each(function(item, idx) {
        if(this.options.count > idx) {
            tr.adopt(
                new Element('td').adopt(
                    new Element('div#blshow', {
                        'events': {
                            'click': function() {
                                window.location.href = CVST.getURL('Desc.jsp?iid=' + item.id);
                            }
                        }
                    }).adopt(
                        new Element('span').adopt(
                            new Element('img[src=../imgs/0/' + item.sku + '.jpg][alt=' + item.sku + ']', {
                                'events': {
                                    'error': function() {
                                        this.setStyle('display', 'none');
//                                        this.set('src', '../img/mold.jpg');
                                    }
                                }
                            })
                        ),
                        new Element('p[text=$' + numberFormat(item.price) + ']'),
                        new Element('div[html=' + item.name + ']')
                    )
                )
            );
            if(! ((idx + 1) % this.options.cols)) {
                tbody.adopt(tr);
                tr = new Element('tr[align=center]');
            }
        }
    }, this);
    this.id.adopt(new Element('table').adopt(tbody));
 }
});

//-----------------------
//
var Search = new Class({
 initialize: function(elm) {
    this.elm = document.id(elm);
    if(!this.elm) return;

    this.args = [];
    this.searchParams();
    this.search = this.args['Search'] || '';
    this.ctitle = this.args['tl'] || '0';
    this.sfill = 'Search for';

    this.go();
 },
 go: function() {

    this.srchIn = new Element('input[type=text][name=Search][value=' + (this.search ? this.search : this.sfill) + ']', {
        'events': {
            'focus': function() {
                this.value = '';
            },
            'mouseenter': function() {
                this.setStyle('background-color', '#ffffef');
            },
            'mouseleave': function() {
                this.setStyle('background-color', '#f3f3f3');
            },
            'keyup': function(ev) {
                if(ev.key === 'enter') {
                    this.butt.fireEvent('click', ev);
                }
            }.bind(this)
        }
    });

    this.elm.adopt(this.srchIn, new Element('tt[text= in ]'));

    var sel = new Element('select', {
        'events': {
            'change': this.onSelect.bind(this)
        }
    }).adopt(
        new Element('option[value=0]' + (this.ctitle === '0' ? '[selected=yes]' : '') + '[text=All Products]'),
        new Element('option[value=1]' + (this.ctitle === '1' ? '[selected=yes]' : '') + '[text=Advanced]')
    );
    this.elm.adopt(sel);

    this.butt = new Element('button[type=submit][text=Search]', {
        'events': {
            'click': this.onSubmit.bind(this)
        }
    });
    this.elm.adopt(this.butt);
 },
 onSelect: function(ev) {
  ev.stop();
  this.ctitle = ev.target.value;
 },
    onSubmit: function(ev) {
        ev.stop();

        if(this.srchIn.value !== this.sfill) {
            var val = this.srchIn.value.replace(/hp/g, 'hpp');
            if(val.length < 3) {
                alert('Must be more 3 letters.');
                return;
            }
            window.location.href = CVST.getURL('Search.jsp?Search=' + escape(this.srchIn.value));
        }
    },
 searchParams: function() {
  var idx = 0,pos,url = document.URL;
  if((idx = url.indexOf('?')) > 0) {
   url = url.substring(idx + 1, url.length);
   url.split('&').each(function(pair) {
    pos = pair.indexOf('=');
    if(pos !== -1) {
      this.args[pair.substring(0, pos)] = unescape(pair.substring(pos + 1));
    }
   }, this);
  }
 }
});
window.addEvent('domready', function(){ new Search('dsrch'); });

//----------------------------
//
var Excel = new Class({
 initialize:function(elm) {
    this.elm = document.id(elm);
    if(!this.elm) return;

    this.elm.adopt(
        new Element('img[src=../img/excel.png][align=top][alt=Download Excel files]'),
        new Element('select[style=width:120px;color:#800000;margin-right:9px;]', {
            'events': {
                'change': this.select.bind(this)
            }
        }).adopt(
            new Element('option[value=0][text=Download Now]'),
            new Element('option[value=1][text=Special Pricing]'),
            new Element('option[value=2][text=Inventory Just Arrived]')
        )
    );
 },
 select: function(ev) {
  switch(ev.target.value) {
    case '1': window.location.href = '../advert/excel/Wholesale Prices.xls'; break;
    case '2': window.location.href = '../advert/excel/JustArrived.xls'; break;
  }
 }
});
window.addEvent('domready', function() {
    new Excel('dsrch');
});

//----------------------------
//
//<a class='tglnk' href='#' name='for open'><b>+</b>head</a>
// <div id='tgbody'>
// bla bla
// </div>
//
var Slides = new Class({
 initialize: function(links) {
    this.links = $$(links);
    if(!this.links) return;

    var uri = new URI(document.location.href);
    this.links.each(function(link) {
        var div = link.getNext(); // <div id='tgbody'>
        if(div) {
            link.addEvent('click', function(ev) {
                div.slide('toggle');
                ev.stop();
                link.getFirst().set('text', div.get('slide').open ? '+' : '-'); // <b>+</b>
            });
            // if have value op=nameforopen - not hide
            if(uri.get('data').op && uri.get('data').op === link.get('name')) {
                link.getFirst().set('text', '-'); // <b>-</b>
            }
            else {
                div.slide('hide');
            }
        }
    });
 }
});
function SlideOpen(block) {
    this.links = $$('a.tglnk');
    this.links.each(function(link) {
        if(link.get('name') === block) {
            var div = link.getNext().getFirst(); // <div id='tgbody'>
            if(div) {
                div.get('slide').toggle();
                link.getFirst().set('text', div.get('slide').open ? '+' : '-'); // <b>-</b>
            }
        }
    });
}

//----------------------------
// <tag id='db' class='tipz'>bla</tag>
// ffox - call twice
// need rebuild
var Tipz = new Class({
 initialize: function(tips) {
  this.tips = $$(tips);
  if(!this.tips) return;
  this.json = '';

  this.wraptip = document.id('wrtip');
  if(!this.wraptip) {
    this.tagTip();
  }

  this.tips.addEvents({
    'mouseenter': this.show.bind(this),
    'mouseleave': this.hide.bind(this)
  });
 },
 tagTip: function() {
  this.wraptip = new Element('div#wrtip').inject(document.body, 'top');
 },
 show: function(ev) {
  var rel = this.wraptip.get('dir');
  if(!rel || rel !== ev.target.id) { // load only one time

    this.wraptip.empty();

    new Request({
        url: '../gettip',
        onSuccess: function(tip) {
            try {
                this.json = eval('(' + tip + ')');
            }
            catch(err){ alert('Error...');return; }

            this.wraptip.set({
                'styles': {
                'width': this.json.wd,
                'background': this.json.bg
                },
                'dir': ev.target.id,
                'html': this.json.txt
            });
        }.bind(this),
        onFailure : function(err) { alert('Error... ' + err); }
    }).send('id=' + ev.target.id);

  }

  this.wraptip.setStyles({
    'top': ev.page.y + 18 + 'px',
    'left': ev.page.x + 'px',
    'display': 'block'
  });
 },
 hide: function() {
  this.wraptip.setStyle('display', 'none');
 }
});
window.addEvent('domready', function(){ new Tipz('img.tipz, span.tipz, a.tipz'); });


//---
// bootom line
var Bottom = new Class({
 initialize:function() {
  this.foot = document.id('cvfoot');
  if(!this.foot) return;

  this.foot.set('html', '\
   <p>\
    <a href="' + CVST.getURL('')                        + '">Home</a> | \
    <a href="' + CVST.getURL('info/AboutUs.jsp')        + '">About Us</a> | \
    <a href="' + CVST.getURL('info/ContactUs.jsp')      + '">Contact Us</a> | \
    <a href="' + CVST.getURL('info/CustomerService.jsp')+ '">Customer Service</a> | \
    <a href="' + CVST.getURL('info/Resellers.jsp')      + '">Resellers</a> | \
    <a href="' + CVST.getURL('info/Returns.jsp')        + '">Returns</a> | \
    <a href="' + CVST.getURL('info/SiteMap.jsp')        + '">Site Map</a> | \
    <a href="' + CVST.getURL('info/Affiliate.jsp')      + '">Affiliate Program</a> | \
    <span id="bsocial"></span> \
   </p>\
   <div>\
    <div class="lft">All Rights Reserved (c) 1996 - 2013 Compuvest Corp.&trade; is operating the following sites:\
     <a href="' + CVST.getURL('./') + '">www.compuvest.com</a>\
    </div><div class="rgt">888.644.7017</div>\
   </div>');
 }
});
window.addEvent('domready', function(){ new Bottom(); });

//---
// twitter and facebook icons
var Social = new Class({
    facebook: '<a href="http://www.facebook.com/pages/Compuvest-Corporation/137501466319430#!/pages/Compuvest-Corporation/137501466319430" style="border-left:none;" target="_blank"><img src="../img/facebook.png" title="Facebook" alt="" style="border:0;width:20px;margin-bottom:-5px;"/></a>',
    twitter: '<a onclick="window.open(\'http://twitter.com/#!/CompuvestCorp\',\'sharer\', \'toolbar=0,status=0,width=700,height=500,resizable=yes,scrollbars=yes\');return false;" style="border-left: medium none;" href="#Twitter"><img src="../img/twitter.png" style="border:0 none;width:20px;margin-bottom:-5px;" alt="" title="Twitter"/></a>',
    initialize:function() {
        var bottom = document.id('bsocial');
        if(bottom) {
            bottom.set('html', this.facebook + this.twitter);
        }
        var head = document.id('hsocial');
        if(head) {
            head.set('html', this.facebook + this.twitter);
        }
    }
});
window.addEvent('domready', function(){ new Social(); });

/* desc tabs */
//--------------------------
//
var cvTabs = new Class({
 Implements: Options,
 options: {
    newtabs: [],
    waitIcon: 'Loading... <img src="../img/wait.gif" alt="wait"/>'
 },
 initialize: function(tabsid, options) {
  this.tbs = document.id(tabsid);
  if(!this.tbs) return;
  this.setOptions(options);

  this.tabs = this.tbs.getElements('a.tab'); // all tabs
  this.panels = this.tbs.getElements('div.panel'); // all panels

  // add new tabs
  if(this.options.newtabs) {
      this.options.newtabs.each(function(tab) {
          this.addTab(tab.id, tab.name, tab.text, tab.ajax, tab.etilid);
      }, this);
  }

  // set first active
  this.tabs.filter('.tab')[0].addClass('active');
  this.panels.filter('.panel')[0].addClass('active');

  // add events
  this.tabs.each(function(elm) {
    elm.addEvents({
      'click': this.setTab.bind(this, elm.get('href')),
      'focus': function() { this.blur(); }
    });
  }, this);

 },
 setTab: function(id, ev) {
  ev.stop();

  // set active
  this.tabs.removeClass('active');
  this.panels.removeClass('active');

  // set active panel
  var elm = this.panels.filterById(id).addClass('active');
  this.tabs.filterByAttribute('href', '=', id).addClass('active');

  // Ajax
  if(elm.retrieve('ajax')[0] === 'on' && elm.get('text')[0].indexOf('Loading...') > -1) {
    new Request({
      url: 'desctabs',
      onSuccess: function(items) {
        if(!items.length) {
            elm.set('html', '<h3 style="padding:10px 0;">We have found 0 items that match</h3>');
            return;
        }

        items = eval('(' + items + ')');
        elm.set('text', '');
        elm.adopt(new Items(items));

        new Tipz('img.tipzb');

        new DialogBox('a.drpab'); // drop price alert

      }.bind(this),
      onFailure : function(err) { alert('Error... (cvTabs) ' + err); }
    }).send('mfrs=' + elm.retrieve('mfrs')[0] + '&nc=' + Math.random());
  }
 },
 addTab: function(id, name, text, ajaxOn, mfrs) {
  //the new tab
  var newA = new Element('a.tab[href=' + id + '][html=<span>' + name + '</span>]', {
    'events': {
        'focus': function() { this.blur(); }
    }
  });
  var newLi = new Element('li', {
    'events': {
        'click': this.setTab.bind(this, id)
    }
  }).adopt(newA);

  // new tab
  this.tabs.include(newA); // add to array
  this.tbs.getElement('ul').adopt(newLi); // add new tabs

  //the new panel
  var newDiv = new Element('div#' + id + '.panel[html=' + (ajaxOn ? this.options.waitIcon : text) + ']');
  newDiv.store('ajax', ajaxOn).store('mfrs', mfrs);

  this.panels.include(newDiv); // add to array
  this.tbs.getElement('div').adopt(newDiv); // add new panel
 }
});

//--------------------------
//
var AdvertRight = new Class({
    Implements: Options,
    options: {
        id: 'advright'
    },
    text:
    'If you are experiencing any difficulties with the usability of our site,' +
    'please notify us with a brief description of the problem so that we can improve to better serve our customers.' +
    'We appreciate your feedback and will compensate your time by sending you a free gift.%0a%0a' +
    'Browser used:%0a%0a%0a%0a' +
    'Problem description:%0a%0a%0a%0a' +
    'Thank you%0a' +
    'CompuVest Technical Team%0d',
    initialize: function(options) {
        this.setOptions(options);
        this.adright = document.id(this.options.id);
        if(!this.adright) return;

//        this.adright.adopt(
//            new Element('a[href=../promo/WholeSale.html][style=text-decoration:none;color:#eaf2ea;]').adopt(
//                new Element('img[src=../promo/WholeSale.jpg][style=margin-top:10px;border:0;][alt=Promo]')
//            ),
//            new Element('p[style=display:none;]').set('text', this.text)
//        ).set('style', 'text-align:center;');

//        this.adright.adopt(
//            new Element('a[href=mailto:webproblem@compuvest.com?subject=Website problem ' + new Date() + '&body=' + this.text + '][style=text-decoration:none;color:gray;]').set('html',
//                'Please help to improve our website by notifying us of any problems. We will send you a gift in appreciation of your time. <b style="color:blue;">Click here</b>.'
//            )
//        );
    }
});
//window.addEvent('domready', function() {
//    new AdvertRight();
//});

//--------------------------
//
var Warning = new Class({
    text: '<p>Warning!</p> \
        Computers and computer circuit boards, as well as other electronic equipment, contain lead, which is a chemical \
        known to the State of California to cause cancer or cause birth defects and other reproductive harm. \
        Please wash hands after handling circuit boards and other internal components of computers and electronic equipment, \
        and avoid inhalation of fumes if heating the solder on the internal components or circuit boards.',

    initialize: function() {
        var warn = document.id('warning');
        if(!warn) return;
        warn.set('html', this.text);
        warn.slide('hide').slide('in');
    }
});

//--------------------------
//
var LeftMenu = new Class({
    Implements: Options,
    options: {
        id: 'leftmenu',
        gid: 0,
        sid: 0,
        data: []
    },
    initialize: function(options) {
        this.setOptions(options);
        this.leftmenu = document.id(this.options.id);
        if(!this.leftmenu || !this.options.data.length) return;

        var lmenu;
        if(this.options.data) {

            lmenu = new Element('div#lmenu');

            var gli,sul,tagA,catName;

            var gul = new Element('ul');
            this.options.data.each(function(gcat) {
                tagA = new Element('a[href=Cats.jsp?cid=' + gcat.id + '][text=' + gcat.nm + ']',{
//                    'events': {
//                        'mouseenter': function() {
//                            console.log('mouseenter this=',this);
//                        },
//                        'mouseleave': function() {
//                            console.log('mouseleave this=', this);
//                        }
//                    }
                });

                sul = this.getSubcatBlock(gcat.id, this.options.sid, gcat.s);

                if(gcat.id === this.options.gid) {
                    tagA.set('style', 'background:#ffffdf;'); // highlight global category

                    new Element('div#smenu').adopt(sul.clone()).inject(this.leftmenu, 'top'); // inject top subcat
                    new Element('div#tmenu').adopt(tagA.clone()).inject(this.leftmenu, 'top'); // inject top cat title

                    // for navigator Cats.jsp and Items.jsp
                    catName = document.id('catName');
                    if(catName) {
                        catName.set('text', gcat.nm);
                    }
                }
                gli = new Element('li').adopt(tagA).inject(gul);

                gli.adopt(sul); // inject to li ul subcat

            }, this);

            gul.inject(lmenu);

        }
        lmenu.inject(this.leftmenu);

        // ebay picture
        //new Element('img[src=../img/ebayreseller.png][style=margin-top:10px;][alt=Ebay Rated Seller]').inject(this.leftmenu);
    },
    getSubcatBlock: function(catid, subid, sblock) {

        if(!sblock.length) return '';

        var ul = new Element('ul'),li,scatName;
        sblock.each(function(scat) {
            li = new Element('li');
            if(subid === scat.id) {
                li.set('style', 'border:1px solid #a6a7b0;background:#e5e7d9;'); // highlight global subcategory

                // for navigator Cats.jsp and Items.jsp
                scatName = document.id('scatName');
                if(scatName) {
                    scatName.set('text', scat.nm);
                }
            }
            li.adopt(new Element('a[href=Items.jsp?cid=' + catid + '&sid=' + scat.id + '][text=' + scat.nm + ']')).inject(ul);
        }, this);

        return ul;
    }

});

//--------------------------
//
/*var LeftMenu1 = new Class({
    Implements: Options,
    options: {
        id: 'leftmenu',
        gid: 0,
        sid: 0
    },
    initialize: function(options) {
        this.setOptions(options);
        var lefttag = document.id(this.options.id);
        console.log('left tag=',lefttag);
        //if(!this.leftmenu) return;

        new Request({
            url: '/web/get',
            method: 'get',
            onRequest: function() {
            },
            onComplete: function(data) {
                var json = eval(data);
                console.log('json=',json);

                this.doMenu(json);
            }.bind(this)
        }).send('exec=leftmenu&nc=' + Date.now());

    },
    doMenu: function(json) {
    },
    getSubcatBlock: function(catid, subid, sblock) {
    }
});*/

//----------------------
//
String.implement({
    stripHTMLTag: function() {
        // .replace(/(<([^>]+)>)/ig, '')
        // .replace(/<&#91;^>&#93;*>/g, '')
        // .replace(/<\S[^><]*>/g, '')
        return this.replace(/<&#91;^>&#93;*>/g, '');
    },
    xmlToHtml: function() {
        return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/\?/g, '').replace(/\u00A6/g, '<br/>');
    }
 });
/*
*/
var Descr = new Class({
 Implements: Options,
 options: {
    data:''
 },
 nospecMessg: 'No specifications available for this product at this time.',
 waitIcon: "<img src='../img/wait.gif' alt='wait'/>",
 initialize:function(tabsid, json) {
    this.tbs = document.id(tabsid);
    if(!this.tbs) return;
    this.setOptions(json);

    // new tabs
    this.newtabs = [];

    // get first tab
    this.tabid = this.tbs.getElement('a.tab').get('href');

    // first panel
    this.panel = this.tbs.getElement('#' + this.tabid);
    this.panel.set('html', this.waitIcon);

    this.json = this.options.data;
    if(this.json && this.json.sku) {
        this.doDescrJSON();
    }
    else {
        this.panel.set('text', this.nospecMessg);
        return;
    }

    new Warning();
 },
 doDescrJSON: function() {
    this.panel.empty();

    // fill images
    var imgbox = document.id('imgbox');
    if(this.json.imgs && imgbox) {
        this.json.imgs.each(function(img, idx) {
            if(idx < 4) { // first 4 images - but need make for 6
                new Element('span',{
                    'html': '<img src="' + IMGURL + img + '/' + this.json.sku + '.jpg" alt="' + this.json.sku + '"/>'
                }).inject(imgbox);
            }
        }, this);
    }
    //
    new Element('div.dshead[text=Marketing Information]').inject(this.panel);
    new Element('div.dsbody',{
        'html': '' + (this.json.minfo ? this.json.minfo.xmlToHtml() : '') + (this.json.nameb ? this.json.nameb.xmlToHtml() : '')
    }).inject(this.panel);
    new Element('hr').inject(this.panel);

//    console.log('this.json.mspec=',this.json.mspec);
    if(this.json.mspec) {
        new Element('div.dshead[text=Main Features]').inject(this.panel);
        var div = new Element('div#tagLI');
        var attr = new Hash(this.json.mspec.attr);
        attr.each(function(val, key) {
            if(key !== 'Standard Warranty' && key !== 'Package Contents') {
                new Element('li',{
                    'html': '<b>' + key + ' : </b><tt>' + val.xmlToHtml() + '</tt>'
                }).inject(div);
            }
        });
        div.inject(this.panel);
    }

    // Technical Specification page
    //console.log('this.json.espec=',this.json.espec);
    if(this.json.espec) {
        var spec = '';
        this.json.espec.each(function(elm) {
            if(elm.name && elm.name !== 'Warranty' && elm.name !== 'Software') {
                spec += "<div class='dshead'>" + elm.name + "</div><div id='tagLI'>";
                //console.log('elm.attr=',elm.attr);
                //elm.attr.each(function(val, key) {
                //    console.log('val=',val,' : key=',key);
                //});
                var attr = new Hash(elm.attr);
                attr.each(function(val, key) {
                    if(key !== 'Package Contents') {
                        spec += "<li><b>" + key + ' : </b><tt>' + val.xmlToHtml() + '</tt></li>';
                    }
                });
                spec += "</div><hr/>";
            }
        });
        if(spec) {
            this.newTab('tb02', 'Technical Specification', spec);
        }
    }

    // Options & Accessories page
    if(this.json.paccl) {
        this.newTab('tb03', 'Options & Accessories', '', 'on', this.json.paccl);
    }

    // Similar Products page
    if(this.json.psiml) {
        this.newTab('tb04', 'Similar Products', '', 'on', this.json.psiml);
    }

 },
 newTab: function(tabid, name, text, ajax, etilid) {
     this.newtabs.include({id: tabid, name: name, text: text, ajax: ajax, etilid: etilid });
 },
 getNewTabs: function() {
     return this.newtabs;
 },
 getImg: function(img) {
    return (img.length > 0) ? '<span><img src="' + img.get('text') + '" alt="' + img.get('text') + '"/></span>' : '';
 }
});

//--------------------------
//
// Assets.js Preloads an array of images (as strings) and returns an array of img elements. does not inject them to the page.
//
var ImageGalery = new Class({
  Implements: Options,
  options: {
    fxParam: {property:'left', duration:1000, transition:Fx.Transitions.Back.easeOut, wait:false},
    interval: 5000, // 5sec
    imgSize: 300 // image width
  },
  currentIndex: null,
  _play: null,
  wait: false,
  initialize: function(bufid, options) {
    this.imgbuf = document.id(bufid);
    if(!this.imgbuf) return;
    this.setOptions(options);

    this.box = this.imgbuf.getElement('#imgbox');
    this.images = this.box.getElements('img');

    this.makeThumbs();

    this.box.setStyle('width', this.options.imgSize * this.images.length + 'px');

    this.imgFx = new Fx.Tween(this.box, this.options.fxParam).set(0);
    this.maskFx = new Fx.Tween(this.thumMask, this.options.fxParam).set('-298px');
    this.walk(0);
 },
 makeThumbs: function() {
    this.thumbs = new Element('div#thumbs');

    this.thumMask = new Element('div#thumbs_mask[style=left:-298px;opacity:0.6;]');
    var handles = new Element('p#thumbs_handles');

    var divs = '';
    this.images.each(function(img,idx) {
        divs += '<div><img src="' + img.src + '" alt=""/></div>';
        handles.adopt(
            new Element('span', {
                'events': {
                    'click': this.walk.bind(this, idx)
//                    'mouseenter': this.walk.bind(this, idx)
//                    'mouseleave': this.walk.bind(this, [idx,true])
                }
            })
        );
    }, this);
    var div = new Element('div.thumbs[html=' + divs + ']');

    this.thumbs.adopt(div, this.thumMask, handles);
    this.thumbs.inject(this.imgbuf, 'after');
 },
 next: function(manual) {
    this.walk((this.currentIndex < this.images.length - 1 ? this.currentIndex + 1 : 0), manual);
 },
 play: function() {
    this._play = this['next'].periodical(this.options.interval, this, [false]);
 },
 stop: function() {
//    $clear(this._play);
 },
 walk: function(item) {
//     console.log('item=',item,' current=',(item != this.currentIndex))
    if(item !== this.currentIndex) {
	this.currentIndex = item;

        // next position
        this.imgFx.start(this.options.imgSize * -this.currentIndex);
        this.maskFx.start(this.currentIndex * 75 - 298);
    }
 }
});

//------------------------------
//
var Items = new Class({
 initialize:function(items) {
  // create tag for big image
  this.bigimg = document.id('bigimg');
  if(!this.bigimg) {
    this.bigimg = new Element('div#bigimg[style=opacity:0;]').inject(document.body, 'top');
  }

  var div = new Element('div#accsum'),item,tr,td,tbody1,tr1;

  // create row table
  var tbody = new Element('tbody');

  for(var i = 0; i < items.its.length; i++) {
    item = items.its[i];

    tr = new Element('tr');

    // image field
    td = new Element('td#cl1');
    new Element('img[src=../imgs/0/' + item.sku + '.jpg][alt=' + item.sku + ']', {
        'events': {
            'mouseenter': this.show.bind(this, item.sku),
            'mouseleave': this.hide.bind(this),
            'error': function() {
                this.setStyle('display', 'none');
//                this.set('src', '../img/mold.jpg');
            }
       }
    }).inject(td);
    tr.adopt(td);

    // descrCVST
    new Element('td#cl2',{'html': '\
        <a href="' + CVST.getURL('Desc.jsp?iid=' + item.id) + '">' + item.nm + '</a>\
        <div><dl><dd>&#187; SKU : ' + item.sku + '\
        </dd><dd>&#187; Condition : ' + item.cnd + '\
        </dd><dd>&#187; Stock : ' + item.qty + '\
        </dd></dl></div><div><dl><dd>&#187; Manufacturer : ' + item.mnm + '\
        </dd><dd>&#187; Manufacturer P/N : ' + item.mfr + '\
        </dd><dd>&#187; Package : ' + item.pkg + '\
        </dd></dl></div>'
    }).inject(tr);

    // price and add basket
    td = new Element('td#cl3');
    tbody1 = new Element('tbody');

    // drop alert
    tr1 = new Element('tr');
    new Element('td.drp[colspan=3][html=<a id="' + item.id + '" class="drpab" href="javascript:;">Drop Price Alert</a>]').inject(tr1);
    tbody1.adopt(tr1);

    this.trTag(item, this.banner(item)).inject(tbody1);

    if(item.it) { // addition item
        this.trTag(item.it , '').inject(tbody1);
    }

    td.adopt(new Element('table').adopt(tbody1));
    tr.adopt(td);

    tbody.adopt(tr);

    // draw dashed bottom border
    if((i + 1) !== items.its.length){ // no need last hr
        tbody.adopt(new Element('tr').adopt(new Element('td[colspan=3]').adopt(new Element('hr'))));
    }
  }

  return div.adopt(new Element('table').adopt(tbody));
 },
 trTag: function(item, elm) {
  return new Element('tr').adopt(
    new Element('td').adopt(elm),
    new Element('td.pr[html=$' + numberFormat(item.prc) + ']'),
    new Element('td[style=width:90px;padding:0 0 3px 0;]').adopt(
      new Element('a#addbk[href=' + CVST.getURL('Basket.jsp?iidd=' + item.id) + ']').adopt(
        new Element('div[text=Add to Cart]')
      )
    )
  );
 },
 banner: function(item) {
  var span = new Element('span[style=font-size:12px;color:teal;]');
  if(item.it) { // addition item
   span.set({'html': 'Special price <img id="spp" class="tipzb" src="../img/hlp.gif" alt=""/>'});
  }
  else if(item.bnr) {
    var fsp = '';
    if(item.bnr.sp)      fsp = "Special Price";
    else if(item.bnr.cl) fsp = "Clearance";
    else if(item.bnr.bp) fsp = "Best Price";
    else if(item.bnr.cs) fsp = "Ships in: 2-5 Days";
    span.set({'text': fsp});
  }
  return span;
 },
 show: function(name, evt) {
  evt.stop();

  this.bigimg.setStyles({
    opacity : 1.0,
    top     : evt.page.y - 100 + 'px',
    left    : evt.page.x + 100 + 'px'
  });

  evt.target.setStyle('opacity' , 0.3);

  new Element('img[src=../imgs/0/' + name + '.jpg][alt=' + name + ']').inject(this.bigimg);
 },
 hide: function(evt) {
  evt.stop();

  evt.target.setStyle('opacity', 1.0);
  this.bigimg.setStyle('opacity', 0).empty();
 }
});


//-----------------------------
//chat
/*var Chat = new Class({
initialize:function(elm) {
    this.elm = document.id(elm);
    if(!this.elm) return;

    this.elm.adopt(
        new Element('a[href=javascript:;]', {
            'events': {
                'click': function(ev) {
                    ev.stop();
                    this.newWindow = window.open('http://livechat.boldchat.com/aid/7567926102590264081/bc.chat?cwdid=1652141698897330397&amp;wdid=1179094119070430670&amp;url='+escape(document.location.href),'Chat','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=480,height=350');
                    this.newWindow.focus();
                    this.newWindow.opener = window;
                }
            }
        }).adopt(
            new Element('img[src=https://cbi.boldchat.com/aid/7567926102590264081/bc.cbi?cbdid=2455636718262289987&amp;wdid=1179094119070430670][alt=Live chat][style=border:0;]')
        )
    );
}
});
window.addEvent('domready', function() {
    new Chat('bchat');
});*/

//-------------------------------------
//
window.addEvent('domready', function() {
  document.getElements('a').addEvent('focus', function() { this.blur(); } );
});

/*
var startTime = Date.now();
alert('done: '+(startTime - Date.now()));
*/
